"""Synchronous SQLAlchemy session for legacy/sync endpoints (e.g., performance)."""

from __future__ import annotations

from typing import Generator

from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker

from ..core.config import settings


def _to_sync_uri(async_uri: str) -> str:
    """Convert an async SQLAlchemy URI to its sync counterpart.

    Supported conversions:
    - sqlite+aiosqlite -> sqlite
    - mysql+aiomysql -> mysql+pymysql
    If no known async driver is found, returns the original URI.
    """
    if "+aiosqlite" in async_uri:
        return async_uri.replace("+aiosqlite", "")
    if "+aiomysql" in async_uri:
        return async_uri.replace("+aiomysql", "+pymysql")
    return async_uri


sync_engine = create_engine(
    _to_sync_uri(settings.SQLALCHEMY_DATABASE_URI),
    echo=settings.DB_ECHO,
    pool_pre_ping=True,
)

SyncSessionLocal = sessionmaker[Session](
    bind=sync_engine,
    autoflush=False,
    autocommit=False,
)


def get_sync_db() -> Generator[Session, None, None]:
    """Yield a synchronous DB session for FastAPI dependencies."""
    db = SyncSessionLocal()
    try:
        yield db
    finally:
        db.close()
